<!--
*  2021-03-15
*  成品 码单新增
-->
<template>
  <div id="app" class="product-code">
    <!-- 头部导航 -->
    <van-nav-bar
      ref="header"
      :title="title"
      left-arrow
      @click-left="onClickLeft"
      left-text="返回"
    >
      <template #right>
        <span @click="onClickRight" v-if="receiveFlag == 0"
          ><van-icon name="plus" size="20"
        /></span>
      </template>
    </van-nav-bar>
    <!-- 总计 -->
    <van-cell
      class="product-code__total"
      v-show="tableData.length !== 0"
      :title="'总长度: ' + totalLength"
    >
      <template slot="default">
        <div>
          <span>{{ "总重量: " + totalWeight }}</span>
          <span>{{ "总匹数: " + totalNum }}</span>
        </div>
      </template>
    </van-cell>
    <!-- 选择客户 -->
    <van-cell
      class="product-code__customer"
      title="选择客户"
      is-link
      :value="customerName"
      @click="onClickSelect"
    >
    </van-cell>
    <!-- 第几批次 -->
    <van-cell class="product-code__daySeq" title="车次号">
      <van-field
        v-model="daySeq"
        :readonly="isDetails"
        @focus="onClickFocus"
        @blur="onClickBlur"
      ></van-field>
    </van-cell>

    <!-- 滚动 -->
    <better-scroll
      class="public-scroll"
      :data="tableData"
      :totalPage="totalPage"
    >
      <van-cell-group v-show="tableData.length !== 0">
        <van-swipe-cell v-for="(data, index) in tableData" :key="index">
          <van-cell
            :title="data.topNo"
            :value="data.color"
            :class="
              data.preCustomerId > 0 && data.preCustomerId != customerId
                ? 'active'
                : data.status != 2
                ? 'error'
                : 'default'
            "
          >
            <template slot="title">
              <div class="product-code__cell">
                <span>
                  <span>缸号: </span><van-field readonly :value="data.dyeSeqNo"
                /></span>
                <span>
                  <span>幅宽:</span>
                  <van-field readonly :value="data.width" />
                </span>
                <span>
                  <span>长度: </span><van-field readonly :value="data.length"
                /></span>
                <span>
                  <span>重量: </span><van-field readonly :value="data.weight"
                /></span>
              </div>
            </template>
            <template #default>
              <span style="color:black">匹号: {{ data.designSeqNo }}</span>
            </template>
          </van-cell>
          <template #right>
            <van-button
              square
              type="danger"
              text="删除"
              @click="onDelete(data, index)"
            />
          </template>
        </van-swipe-cell>
      </van-cell-group>
      <van-empty
        class="custom-image"
        image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
        v-show="tableData.length === 0"
        description="暂无数据"
      />
    </better-scroll>

    <van-cell-group
      class="product-code__btn"
      v-if="tableData.length && receiveFlag == 0"
    >
      <van-button block type="info" class="bgColor" @click="onClickConfirmAdd"
        >确认新增</van-button
      >
      <!-- <van-button
        block
        type="info"
        class="bgColor"
        v-permissions="'100103'"
        v-if="noteId != '' && receiveFlag != 1"
        @click="onClickConfirmReceive"
        >接 收</van-button
      > -->
    </van-cell-group>

    <!-- 选择客户 -->
    <!-- <van-popup v-model="showPicker" position="bottom" get-container="body">
      <van-picker value-key="value" :columns="columns" @change="onConfirm">
      </van-picker>
    </van-popup> -->
    <van-action-sheet
      class="product-code__sheet"
      v-model="showPicker"
      :actions="columns"
      close-on-click-action
      @select="onConfirm"
      get-container="body"
    >
      <template slot="description">
        <van-search
          v-model="name"
          type="text"
          placeholder="输入名称"
          clearable
          @search="onGetCustomerList"
        ></van-search>
      </template>
    </van-action-sheet>
  </div>
</template>

<script>
import { openWin, getFloat, deepCopy } from "@/utils/index";
import {
  getCustomerInfoList,
  getClothNoteScanAdd,
  getClothNoteScan,
  getClothNoteDetails,
  getClothNoteReceiveNote,
  getClothNoteDel,
  getProductStoreScanCheckDetail, loadCustomerChannelData,
} from "@/api/product";
import { getMacAddress } from "@/utils/auth";
import {SPLIT_BLANK, SPLIT_XHX} from "@/api/enum";

export default {
  name: "productCode",
  data() {
    return {
      title: "",
      currentPage: 1,
      totalPage: 1,
      tableData: [],
      yHeight: 0,
      totalLength: 0,
      totalWeight: 0,
      totalNum: 0,
      customerName: "",
      customerId: "",
      daySeq: 1,
      name: "",
      columns: [],
      showPicker: false,
      isDetails: false,
      noteId: "",
      printStatus: false,
      isPrint: false,
      receiveFlag: 0,

      /* 渠道 */
      channels: [],
    };
  },
  watch: {
    // 监听码单数组
    tableData: {
      handler(val) {
        this.totalLength = getFloat(this.countTotal(val, "length"), 1);
        this.totalWeight = getFloat(this.countTotal(val, "weight"), 1);
        this.totalNum = this.tableData.length;
      },
      deep: true,
    },
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      this.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }
  },
  methods: {
    //初始化
    initFn(that) {
      loadCustomerChannelData({}, data => {
        data.forEach(channel => {
          that.channels.push({
            value: channel.key,
            label: channel.value,
          });
        });
      });


      that.isDetails = window.api.pageParam.isDetails;
      that.noteId = window.api.pageParam.noteId;
      that.receiveFlag = window.api.pageParam.receiveFlag;
      that.daySeq = window.api.pageParam.daySeq;
      if (window.api.pageParam.tableData && window.api.pageParam.tableData.length) {
        that.tableData = window.api.pageParam.tableData;
      }
      if (window.api.pageParam.isOut) {
        that.title = that.receiveFlag == 1 ? "成品码单详情" : "新增成品码单";
        that.customerName = window.api.pageParam.customerName;
        that.customerId = window.api.pageParam.customerId;
      } else {
        if (that.isDetails) {
          that.title = that.receiveFlag == 1 ? "成品码单详情" : "新增成品码单";
          that.customerName = window.api.pageParam.customerName;
          that.customerId = window.api.pageParam.customerId;
          that.onGetClothNoteDetails();
        } else {
          that.title = "新增成品码单";
          that.onClickRight();
          that.onGetCustomerList();
        }
      }
      window.api.addEventListener({
        name:'viewdisappear'
      }, function() {
        window.api.closeWin();
      });
    },
    // 返回
    onClickLeft() {
      openWin("product");
    },
    // 获取详情 打印
    onGetClothNoteDetails() {
      getClothNoteDetails(
        {
          noteId: this.noteId,
        },
        (res) => {
          this.tableData = res;
        }
      );
    },
    // 扫码
    onClickRight() {
      const that = this;
      const zyHmsScan = api.require('zyHmsScan');
      zyHmsScan.openDefaultView({}, ret => {
        if(ret.status) {
          let content = ret.result;
          if (content.indexOf("15,") != -1) {
            // 成品盘库码  获取成品详情
            getProductStoreScanCheckDetail(
                {
                  checkId: content.split(",")[1],
                },
                (respon) => {
                  let res = window.api.pageParam;
                  res.respon = respon;
                  res.tableData = that.tableData;
                  openWin("product-storeOut", res);
                }
            );
          } else {
            // 成品码
            if (content.indexOf("http://") == -1) {
              let index = content.indexOf("flag");
              let flag = index != -1 ? 1 : "";
              let params = {};
              if (flag) {
                let lastIndex2 = content.indexOf("?");
                params.geryClothId = content.slice(0, lastIndex2);
                params.flag = flag;
              } else {
                params.geryClothId = content;
              }
              getClothNoteScan(params, (res) => {
                if (that.tableData.length != 0) {
                  let index = that.tableData.findIndex(
                      (item) => item.id === res.id
                  );
                  if (index === -1) {
                    that.tableData.push(res);
                    that.$toast({
                      type: "loading",
                      message: "请等待",
                      duration: 500,
                      onClose: () => {
                        that.onClickRight();
                      },
                    });
                  } else {
                    that.$toast.fail("请勿重复扫码");
                    return false;
                  }
                } else {
                  that.tableData.push(res);
                  that.$toast({
                    type: "loading",
                    message: "请等待",
                    duration: 500,
                    onClose: () => {
                      that.onClickRight();
                    },
                  });
                }
              });
            } else {
              let index = content.indexOf("flag");
              let flag = index != -1 ? 1 : "";
              let params = {};
              if (flag) {
                let lastIndex = content.lastIndexOf("/");
                let lastIndex2 = content.indexOf("?");
                params.geryClothId = content.slice(lastIndex + 1, lastIndex2);
                params.flag = flag;
              } else {
                let lastIndex = content.lastIndexOf("/");
                params.geryClothId = content.slice(lastIndex + 1, content.length);
              }
              getClothNoteScan(params, (res) => {
                if (that.tableData.length != 0) {
                  let index = that.tableData.findIndex(
                      (item) => item.id === res.id
                  );
                  if (index === -1) {
                    that.tableData.push(res);
                    that.$toast({
                      type: "loading",
                      message: "请等待",
                      duration: 500,
                      onClose: () => {
                        that.onClickRight();
                      },
                    });
                  } else {
                    that.$toast.fail("请勿重复扫码");
                    return false;
                  }
                } else {
                  that.tableData.push(res);
                  that.$toast({
                    type: "loading",
                    message: "请等待",
                    duration: 500,
                    onClose: () => {
                      that.onClickRight();
                    },
                  });
                }
              });
            }
          }
        }
      });
    },
    // 获取客户列表
    onGetCustomerList() {
      const that = this;
      that.columns = [];
      getCustomerInfoList({
        name: that.name,
      }, res => {
        if (res.list.length) {
          res.list.forEach((item) => {
            let channel = that.channels.find(c => c.value == item.channel);
            if(channel) {
              channel = channel.label;
            } else {
              channel = SPLIT_BLANK;
            }
            that.columns.push({
              id: item.id,
              value: item.company,
              name: channel + SPLIT_XHX + item.company + SPLIT_XHX + item.name
            });
          });
        }
      });
    },
    // 选择客户
    onClickSelect() {
      if (!this.isDetails) {
        this.showPicker = true;
      }
    },
    // 确认客户
    onConfirm(customer) {
      const that = this;
      that.customerId = customer.id;
      that.customerName = customer.value;
      that.showPicker = false;
    },
    // 新增码单
    onClickConfirmAdd() {
      if (!this.customerId) {
        this.$toast.fail("请选择客户");
        return false;
      }
      let details = [];
      // this.tableData.forEach((item) => {
      //   details.push({
      //     id: item.id,
      //   });
      // });
      let newArr = deepCopy(this.tableData).filter((item) => item.noteId == 0);
      newArr.forEach((item) => {
        if (item.id) {
          details.push({
            id: item.id,
            stockFlag: 0,
          });
        } else {
          details.push({
            storeId: item.storeId,
            length: item.length,
            area: item.area,
            stockFlag: 1,
          });
        }
      });
      // alert(JSON.stringify(details));
      getClothNoteScanAdd(
        {
          id: this.noteId,
          customerId: this.customerId,
          daySeq: this.daySeq,
          details: details,
        },
        () => {
          this.$toast({
            type: "success",
            message: "新增码单成功",
            duration: 1000,
            onClose: () => {
              openWin("product");
            },
          });
        }
      );
    },
    // 确认接收
    onClickConfirmReceive() {
      getClothNoteReceiveNote(
        {
          noteId: this.noteId,
        },
        () => {
          this.$toast({
            type: "success",
            message: "接收成功",
            duration: 1000,
            onClose: () => {
              openWin("product");
            },
          });
        }
      );
    },
    // 删除
    onDelete(data, index) {
      if (this.receiveFlag == 0) {
        // 判断是否已绑定
        if (data.noteId == 0) {
          this.tableData.splice(index, 1);
        } else {
          getClothNoteDel(
            {
              id: data.id,
            },
            () => {
              this.tableData.splice(index, 1);
            }
          );
        }
      }
    },
    //
    onClickFocus() {
      this.daySeq = "";
    },
    onClickBlur() {
      if (this.daySeq == "") {
        this.daySeq = 1;
      }
    },
    // 计算总重量/总长度
    countTotal(arr, keyName) {
      let $total = 0;
      $total = arr.reduce(function (total, currentValue) {
        console.log(currentValue[keyName]);
        return currentValue[keyName]
          ? total + Number(currentValue[keyName])
          : Number(total);
      }, 0);
      return $total;
    },
    // 判断蓝牙是否打开
    isEnabledBluetooth() {
      const that = this;
      that.printStatus = true;
      window.api
        .require("cxgBluetoothBase")
        .isEnabledBluetooth({}, (ret, err) => {
          if (!err) {
            if (ret.state) {
              // 已打开
              if (!getMacAddress()) {
                this.$toast.fail("如需打印，请退出登录选择打印机");
                return false;
              }
              that.getConnectState();
            } else {
              that.openBluetooth();
            }
          } else {
            that.$toast.fail("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 打开蓝牙
    openBluetooth() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .openBluetooth({}, function (ret, err) {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.connectBleByMacAddress();
            }
          } else {
            that.listenBluetoothStatus();
          }
        });
    },
    // 监听蓝牙连接状态
    listenBluetoothStatus() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .listenBluetoothStatus({}, function (ret, err) {
          if (!err) {
            if (ret.status === "STATE_ON") {
              that.connectBleByMacAddress();
            }
          } else {
            that.$toast.fail("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 查询打印机连接状态
    getConnectState() {
      const that = this;
      that.$toast({
        message: "正在打印",
        type: "loading",
        duration: 20000,
      });
      var obj = window.api.require("xGprinterPlus");
      var ret = obj.getConnectState();
      if (ret.status) {
        let result = false;
        ret.state.forEach((bool) => {
          if (bool) {
            result = bool;
          }
        });
        if (result) {
          // 已连接
          that.$toast.clear();
          if (that.printStatus) {
            that.printLabel();
          }
        } else {
          // 未连接
          that.$toast({
            type: "fail",
            message: "未连接, 请等待",
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddress();
            },
          });
        }
      } else {
        // 未连接
        that.$toast({
          type: "fail",
          message: "未连接, 请等待",
          duration: 1500,
          onClose: () => {
            that.connectBleByMacAddress();
          },
        });
      }
    },
    // 设置打印模式
    setPrinterCommandType() {
      const that = this;
      let obj = window.api.require("xGprinterPlus");
      obj.setPrinterCommandType(
        {
          commandType: 1,
        },
        function (ret) {
          if (ret.status) {
            // 票据模式
            that.printLabel();
          }
        }
      );
    },
    // 连接蓝牙
    connectBleByMacAddress() {
      const that = this;
      if (that.printStatus) {
        that.$toast({
          message: "初始化打印机",
          type: "loading",
          duration: 20000,
        });
      }
      var demo = window.api.require("xGprinterPlus");
      demo.connectBleByMacAddress(
        {
          macAddress: getMacAddress() ? getMacAddress().address : "",
        },
        function (ret, err) {
          if (ret.status) {
            if (ret.message === "已连接") {
              if (that.printStatus) {
                that.$toast({
                  type: "success",
                  message: "连接成功",
                  duration: 1500,
                  onClose: () => {
                    // that.setPrinterCommandType()
                    that.printLabel();
                  },
                });
              }
            } else if (ret.message === "连接失败") {
              that.$toast({
                type: "fail",
                message: "初始化失败",
                duration: 1500,
              });
            }
          } else {
            that.$toast({
              type: "fail",
              message: err.msg,
              duration: 1500,
            });
          }
        }
      );
    },
    // 打印数据
    printLabel() {
      const that = this;
      var obj = window.api.require("xGprinterPlus");
      obj.printLabel({
        rows: [
          {
            lineType: "size",
            width: 80,
            height: 10,
          },
          {
            lineType: "gap",
            data: 0,
          },
          {
            lineType: "cls",
          },
          {
            lineType: "gap",
            data: 0,
          },
        ],
      });

      let rows = [
        {
          lineType: "size",
          width: 80,
          height: that.yHeight + 20,
        },
        {
          lineType: "gap",
          data: 0,
        },
        {
          lineType: "cls",
        },
        {
          lineType: "gap",
          data: 0,
        },
        {
          // 日期
          lineType: "text",
          x: 16 + 2,
          y: 8,
          rotation: 0,
          xscal: 1,
          yscal: 3,
          data: "日期：" + that.dateTime,
        },
        {
          // 总长度
          lineType: "text",
          x: 16 + 2,
          y: 90,
          rotation: 0,
          xscal: 1,
          yscal: 2,
          data: "总长度：" + that.totalLength,
        },
        {
          // 总重量
          lineType: "text",
          x: 16 + 220 + 2,
          y: 90,
          rotation: 0,
          xscal: 1,
          yscal: 2,
          data: "总重量：" + that.totalWeight,
        },
        {
          // 总匹数
          lineType: "text",
          x: 16 + 440 + 2,
          y: 90,
          rotation: 0,
          xscal: 1,
          yscal: 2,
          data: "总匹数：" + that.totalNum,
        },
        {
          // 横线
          lineType: "bar",
          x: 0,
          y: 148,
          width: 608,
          height: 2,
        },
      ];
      let parentYH = 100;
      that.tableData.forEach((items, m) => {
        parentYH = parentYH + 60;
        console.log(parentYH, m);
        let parentParams = {
          // 编号
          lineType: "text",
          x: 16 + 2,
          y: parentYH,
          rotation: 0,
          xscal: 1,
          yscal: 2,
          data: "编号：" + items.details[0].designNo,
        };
        rows.push(parentParams);
        rows.push({
          // 匹数
          lineType: "text",
          x: 16 + 300 + 2,
          y: parentYH,
          rotation: 0,
          xscal: 1,
          yscal: 2,
          data: items.details.length + "匹",
        });
        items.details.forEach((item, n) => {
          let yH = parentYH + 60 * (n + 1);

          let childParamsLength = {
            // 长度
            lineType: "text",
            x: 16 + 2 + 20,
            y: yH,
            rotation: 0,
            xscal: 1,
            yscal: 2,
            data: "长度：" + item.length,
          };
          let childParamsWeight = {
            // 重量
            lineType: "text",
            x: 16 + 220 + 2 + 20,
            y: yH,
            rotation: 0,
            xscal: 1,
            yscal: 2,
            data: "重量：" + item.weight,
          };
          rows.push(childParamsLength, childParamsWeight);
          if (n === items.details.length - 1) {
            parentYH = yH;
            rows.push({
              // 横线
              lineType: "bar",
              x: 0,
              y: yH + 55,
              width: 608,
              height: 2,
            });
          }
        });
      });
      console.log(rows);
      setTimeout(() => {
        obj.printLabel(
          {
            rows: rows,
          },
          function (ret, err) {
            if (ret.status) {
              if (ret.status) {
                that.$toast.success("打印成功");
              }
            } else {
              that.$toast({
                type: "fail",
                message: err.code + err.msg,
                duration: 1500,
                onClose: () => {
                  that.connectBleByMacAddress();
                },
              });
            }
          }
        );
      }, 500);
      setTimeout(() => {
        obj.printLabel({
          rows: [
            {
              lineType: "size",
              width: 80,
              height: 10,
            },
            {
              lineType: "gap",
              data: 0,
            },
            {
              lineType: "cls",
            },
            {
              lineType: "gap",
              data: 0,
            },
          ],
        });
      }, 1000);
    },
  },
};
</script>

<style lang="scss">
.product-code {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .van-search {
    width: 100%;
    position: relative;
    z-index: 999;
  }
  .van-nav-bar__right {
    span {
      display: flex;
      height: 100%;
      align-items: center;
    }
  }
  .product-code__total {
    position: relative;
    z-index: 999;
    span {
      color: #1989fa;
      font-size: 16px;
    }
    .van-cell__title {
      flex: 0 0 36%;
    }
    .van-cell__value {
      & > div {
        display: flex;
        justify-content: space-between;
        span {
          display: line-block;
          flex: 1;
          &:first-child {
            text-align: center;
          }
        }
      }
    }
  }
  .product-code__daySeq {
    .van-cell {
      padding: 0;
      .van-field__control {
        text-align: end;
      }
    }
  }
  .public-scroll {
    flex: 1;
    overflow: hidden;
    .van-cell {
      &.active {
        background: #e6a23c;
        span {
          color: #fff;
        }
        .van-cell.van-field {
          color: #fff;
        }
      }
      &.error {
        background: rgba(255, 0, 0, 0.5);
        span {
          color: #fff;
        }
        .van-cell.van-field {
          color: #fff;
        }
      }
    }
    .van-cell__title {
      flex: 0 0 70%;
    }
    .product-code__cell {
      display: flex;
      flex-wrap: wrap;
      & > span {
        display: flex;
        width: 50%;
        height: 30px;
        align-items: center;
        & > span {
          width: 60px;
        }
        .van-cell.van-field {
          padding-left: 0;
        }
      }
    }
    .van-button {
      height: 100%;
    }
  }
  .product-code__btn {
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    padding: 16px;
    background: whitesmoke;
    &.van-hairline--top-bottom::after,
    .van-hairline-unset--top-bottom::after {
      border-width: 0;
    }
    .van-button {
      margin-bottom: 10px;
    }
  }
}
.van-picker__cancel,
.van-picker__confirm {
  display: none;
}

.van-action-sheet {
  height: 60%;
  overflow: auto;
}
.van-popup--bottom.van-popup--round {
  border-radius: 0;
}
.product-code__sheet {
  width: 100%;
  height: 60%;
}
</style>
